package com.cloudbroker.bcs.common.zookeeper.factory;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudbroker.bcs.common.util.HSBCSProperties;
import com.cloudbroker.bcs.common.zookeeper.ZooKeeperClient;

public class HSBCSZooKeeperClientFactory {
    
    private static final Logger LOG = LoggerFactory.getLogger(HSBCSZooKeeperClientFactory.class);
    
    public static final String ZOOKEEPER_CONNECTSTRING = HSBCSProperties.PROP_NAME_PREFIX
            + "zookeeper.connectString";
    
    public static ZooKeeperClient createZooKeeperClient(String basePath) {
        String zookeeperConnectString = System.getProperty(ZOOKEEPER_CONNECTSTRING);
        if (StringUtils.isBlank(zookeeperConnectString)) {
            zookeeperConnectString = HSBCSProperties.getProperty(ZOOKEEPER_CONNECTSTRING);
        }
        if (StringUtils.isNotBlank(zookeeperConnectString)) {
            if (StringUtils.isNotBlank(basePath)) {
                basePath = ZooKeeperClient.buildFullPath(basePath);
                // 先不带基路径连接，连接后确认（创建）基路径
                ZooKeeperClient zkClient = new ZooKeeperClient(zookeeperConnectString);
                zkClient.start();
                zkClient.mkdirs(basePath);
                zkClient.close();
                // 组装完整的连接串
                zookeeperConnectString += basePath;
            }
            ZooKeeperClient zkClient = new ZooKeeperClient(zookeeperConnectString);
            LOG.info("create ZooKeeperClient of: " + zookeeperConnectString);
            zkClient.start();
            return zkClient;
        } else {
            LOG.error(ZOOKEEPER_CONNECTSTRING + " not configured yet, create ZooKeeperClient failed!!!");
            return null;
        }
    }
    
    public static ZooKeeperClient createZooKeeperClient() {
        return createZooKeeperClient(null);
    }
    
}
